/*
 * @Author: MiNine
 * @Date: 2020-09-19 09:29:01
 * @LastEditors: MiNine
 * @LastEditTime: 2020-09-29 15:23:25
 * @Description: 
 */


const {
  Client
} = require('../models/clientModel');
const {
  Admin
} = require('../models/adminModel')

//引入getmd5以加密
const {
  getMd5
} = require('../utils/crypto');

//引入jwt以添加token
const jwt = require('jsonwebtoken');
const {
  TOKEN_KEY
} = require('../utils/const');
const {
  report
} = require('../routes/clientRouter');
const {
  getRandom
} = require('../utils/randomStr')
//根据客户的_id将其删除
async function delMyClient(req, res) {
  const {
    _id
  } = req.body;
  try {
    //根据_id在数据库内进行查找并删除
    const data = await Client.findOneAndDelete({
      _id
    });
    console.log(data)
    await Admin.findByIdAndUpdate(data.belongAdminId, {
      $pull: {
        clientList: _id
      }
    })
    if (data) {
      res.send({
        status: 1,
        message: '删除成功'
      })
    } else {
      res.send({
        status: 0,
        message: '删除失败'
      })
    }

  } catch (error) {
    console.log('删除失败', error);
    res.send({
      status: 0,
      message: '删除失败'
    })
  }

}

//客户运用账号密码进行登录
async function loginClient(req, res) {
  const {
    account,
    password
  } = req.query;
  const newPassword = getMd5(password)
  const isAccount = await Client.find({
    account
  })
  if (isAccount.length > 0) {
    const isPassword = await Client.find({
      account,
      password: newPassword
    })
    if (isPassword.length > 0) {
      //生成token
      const token = jwt.sign({
          account
        },
        TOKEN_KEY, {
          expiresIn: 60 * 60 * 12
        }
      );
      const findClient = await Client
        .findById(isPassword[0]._id, {
          password: 0,
          onceCode: 0
        })
        .populate("insureOrdList")
        .populate("claimOrdList")
        .populate("belongAdminId", "nickName");
      //返回登陆成功后的信息和token
      res.send({
        status: 1,
        msg: '登录成功',
        token,
        clientData: findClient
      })
    } else {
      res.send({
        msg: "登录失败，密码错误",
        status: '0'
      })
    }
  } else {
    res.send({
      msg: "登录失败,账号不存在",
      status: '0'
    })
  }

}


//客户注册
async function registerClient(req, res) {
  let {
    account,
    password,
    nickName,
    gender,
    isPopularize,
    belongAdminId
  } = req.body;

  nickName = nickName || "client";
  gender = gender || "2";
  isPopularize = isPopularize || false;

  //判断该账户是否在数据库内存在
  const isExit = await Client.find({
    account
  });
  if (isExit.length > 0) {
    res.send({
      status: '0',
      msg: '注册失败，该账户已存在'
    })
  } else {
    const newPassword = getMd5(password);
    //若销售id不为空，将isPopularize改为ture，再在数据库添加新数据
    if (belongAdminId) {
      isPopularize = true;
      const newaccount = await Client.create({
        account,
        password: newPassword,
        nickName,
        gender,
        isPopularize,
        belongAdminId
      })
      //在销售员处进行双向绑定
      await Admin.findByIdAndUpdate(belongAdminId, {
        $push: {
          clientList: newaccount._id
        }
      })
    }

    //若销售id为空，将isPopularize改为false，再从销售员数据库中随机分配一个销售员
    else {
      const data = await Admin.find();
      //获取所有销售员
      const seller = data.filter(element => element.permission === 5)
      //随机获取一名销售员
      const sel = parseInt(Math.random() * seller.length);
      const newaccount = await Client.create({
        account,
        password: newPassword,
        nickName,
        gender,
        isPopularize: false,
        belongAdminId: seller[sel]._id
      })
      //在销售员处进行双向绑定
      await Admin.findByIdAndUpdate(seller[sel]._id, {
        $push: {
          clientList: newaccount._id
        }
      })
      res.send({
        status: '1',
        msg: '注册成功'
      })
    }
  }
}

//查看目标销售员负责的所有客户
async function getMyClient(req, res) {
  try {
    const {
      _id
    } = req.query;
    //根据销售员_id返回其所有客户
    const data = await find({
      belongAdminId: _id
    })
    res.send({
      status: 1,
      msg: "获取客户成功",
      data
    })
  } catch (error) {
    res.send({
      status: 0,
      msg: '获取客户失败'
    })
  }
}

//查看所有客户信息
async function getClients(req, res) {
  const clients = await Client.find().populate({
    path: 'belongAdminId'
  })
  if (clients) {
    res.send({
      status: 1,
      msg: '获取当前用户信息成功',
      clients
    })
  } else {
    res.send({
      status: 0,
    })
  }
}

/*
 * @Author: 岸舟
 * @Date: 2020-09-19 10:58:33
 * @LastEditors: 岸舟
 * @LastEditTime: 2020-09-19 16:55:03
 * @Description: 修改用户信息功能（此处未做过于复杂的判断）    
 */

async function modMyClient(req, res) {

  try {
    const {
      _id, //用户_id
      account,
      nickName,
      gender,
    } = req.body
    const list = await Client.find({
      _id
    })
    if (list.length.length == 0) {
      res.send({
        status: 0,
        type: "修改失败",
        msg: "此用户不存在"
      })
    } else {
      const reapet = await Client.find({
        account
      });
      if (reapet.length > 0 && _id != reapet[0]._id) {
        res.send({
          status: 0,
          msg: "账户名重复，修改失败"
        })
      } else {
        await Client.update({
          _id
        }, {
          account
        })
        await Client.update({
          _id
        }, {
          nickName
        })
        await Client.update({
          _id
        }, {
          gender
        })
        res.send({
          status: 1,
          type: "修改成功",
        })
      }

    }
  } catch (err) {
    console.log(err);
    res.send({
      status: 0,
      type: "修改失败",
      msg: err
    })
  }
}
/**
 * @name: 遗忘密码,通过onceCode修改密码
 * @param {type} 
 * @return {type} 
 */
async function forgetClient(req, res) {
  const {
    account,
    onceCode,
    newPassword
  } = req.body;
  try {
    const findClient = await Client.findOne({
      account
    });
    if (findClient) {
      if (findClient.onceCode == onceCode) {
        await Client.updateOne(findClient, {
          onceCode: getRandom(),
          password: getMd5(newPassword)
        })
        res.send({
          status: 1,
          msg: "修改密码成功!"
        })
        return;
      } else {
        res.send({
          status: 0,
          msg: "援助码错误!"
        })
        return;
      }
    } else {
      res.send({
        status: 0,
        msg: "不存在该账号!"
      })
      return;
    }
  } catch (error) {
    console.log("ERROR!forgetClient" + error);
    res.send({
      status: 0,
      msg: "ERROR",
    })
    return;
  }

}

/**
 * @name: 根据ID获取Client
 * @param {type} 
 * @return {type} 
 */
async function getOneClient(req, res) {
  const {
    _id
  } = req.query;
  try {
    const findClient = await Client
      .findById(_id, {
        password: 0,
        onceCode: 0
      })
      .populate("insureOrdList")
      .populate("claimOrdList")
      .populate("belongAdminId", "nickName");

    if (findClient) {
      res.send({
        status: 1,
        msg: "getOneClient successful",
        data: findClient
      })
      return;
    } else {
      res.send({
        status: 0,
        msg: "no target! getOneClient fail",
      })
      return;
    }
  } catch (error) {
    console.log("ERROR!getOneClient" + error);
    res.send({
      status: 0,
      msg: "ERROR",
    })
    return;
  }

}

/**
 * @name: 
 * @param {type} 
 * @return {type} 
 */
async function updateOneClient(req, res) {
  const {
    _id,
    updateDate
  } = req.body;
  if (updateDate.password) updateDate.password = getMd5(updateDate.password);
  try {
    const updateClient = await Client.updateOne({
      _id
    }, updateDate);
    if (updateClient) {
      res.send({
        status: 1,
        msg: "updateClient successful",
      })
    } else {
      res.send({
        status: 0,
        msg: "updateClient fail",
      })
    }
  } catch (error) {
    console.log("ERROR!updateOneClient" + error);
    res.send({
      status: 0,
      msg: "ERROR",
    })
  }


}
module.exports = {
  delMyClient,
  loginClient,
  registerClient,
  getMyClient,
  getClients,
  modMyClient,
  forgetClient,
  getOneClient,
  updateOneClient
}